package note.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import note.dao.ArticleDao;
import note.dao.entity.Article;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import core.util.AbstractController;
import core.util.Constants;
import core.util.Page;
import core.util.StringHashMap;
import core.util.StringUtil;

/**
 * @author songduk park
 * 
 */
@Controller
public class ArticleController extends AbstractController {
	static final int ROWS_A_PAGE = 100;

	@RequestMapping("/article/listArticle.web")
	public String listArticle(HttpServletRequest request,
			HttpServletResponse response) {

		ArticleDao dao = new ArticleDao(sessionFactory);

		StringHashMap map = dao.createMap();

		String key = request.getParameter("key");
		if (StringUtil.isBlank(key) == false)
			map.put("key", "%" + key + "%");

		int rowSize = dao.listArticleSize(map);

		Page page = makePage(request, rowSize, ROWS_A_PAGE);
		putPageToMap(page, map);

		request.setAttribute(Constants.page, page);

		List<Article> list = dao.listArticle(map);
		request.setAttribute(Constants.list, list);

		return "listArticle";
	}

	@RequestMapping("/article/saveArticle.web")
	public void saveArticle(HttpServletRequest request,
			HttpServletResponse response) {

		ArticleDao dao = new ArticleDao(sessionFactory);

		Article article = new Article();
		article.id = getIntParameter(request, "id");
		article.title = request.getParameter("value");

		if (article.id == 0)
			dao.saveArticle(article);
		else
			dao.updateArticle(article);
	}

	@RequestMapping("/article/deleteArticle.web")
	public void deleteArticle(HttpServletRequest request,
			HttpServletResponse response) {

		ArticleDao dao = new ArticleDao(sessionFactory);

		Article article = new Article();
		article.id = getIntParameter(request, "id");
		article.title = request.getParameter("value");

		if (article.id != 0)
			dao.deleteArticle(article);
	}

}
